package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import messages.*;

/**
 *
 * @author Mariam
 */
public class ThreadReceiveMsg extends Thread {

    private DatagramSocket socket;
    private boolean running;
    private ChatNI parent;

    public ThreadReceiveMsg(DatagramSocket socket, ChatNI parent) {
        this.socket = socket;
        this.running = true;
        this.parent = parent;
    }

    public void kill() {
        running = false;
    }

    @Override
    public void run() {
        try {
            byte[] recvData;
            DatagramPacket myPacket;

            int size;

            while (running) { //récupère taille buffer réception
                size = socket.getReceiveBufferSize();
                recvData = new byte[size];
                myPacket = new DatagramPacket(recvData, recvData.length);
                socket.receive(myPacket);

                System.out.println("Waiting for a message...");

                Message recvMessage = MessagesFactory.getMessage(myPacket.getData());

                System.out.println("A message has been received !");
                System.out.println("Type of the message " + recvMessage.getClass());
                System.out.println("It comes from " + recvMessage.getUsername() + "@" + recvMessage.getHostName() + "\n");
                analyzeMsg(recvMessage);
                recvData = null;
                myPacket = null;
            }

        } catch (IOException ex) {
            Logger.getLogger(ThreadSendMsg.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MessageCreationException ex) {
            Logger.getLogger(ThreadReceiveMsg.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private void analyzeMsg(Message recvMessage) {
        try {
            System.out.println(InetAddress.getByName(recvMessage.getHostName()).toString());
            if (recvMessage.getUsername().equals(parent.model.getLocalUser().getUsername())) {
                System.out.println("Message sent by myself");
            } else {
                if (recvMessage instanceof Hello) {
                    parent.helloRcvd(recvMessage.getUsername(), recvMessage.getHostName());
                    if (((Hello) recvMessage).getWaitAck()) {
                        System.out.println("Remote App is waiting for an ACK");
                        this.parent.sendHelloAck(recvMessage.getHostName());

                    } else {
                        System.out.println("Remote App doesn't want an ACK");
                    }
                } else if (recvMessage instanceof ChatMessage) {
                    System.out.println("The following message has been received :");
                    System.out.println(recvMessage.getUsername() + "@" + recvMessage.getHostName() + " : " + ((ChatMessage) recvMessage).getMsgToSend());
                    parent.msgRcvd(recvMessage.getUsername(), recvMessage.getHostName(), ((ChatMessage) recvMessage).getMsgToSend());
                } else if (recvMessage instanceof Bye) {
                    parent.byeRcvd(recvMessage.getUsername(), recvMessage.getHostName());
                } else if (recvMessage instanceof FileNotif) {
                    if (((FileNotif) recvMessage).getRequest()) {
                        parent.fileRequestRcvd(recvMessage.getUsername(), ((FileNotif) recvMessage).getNameFile(), ((FileNotif) recvMessage).getLengthFile() );
                    } else {
                        parent.fileAnswerRcvd(recvMessage.getUsername(), ((FileNotif) recvMessage).getNameFile(),
                                ((FileNotif) recvMessage).getAccepted());
                    }
                }


            }
        } catch (UnknownHostException ex) {
            Logger.getLogger(ChatNI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}